<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        #myid{
            border: black 1px solid;
        }
    </style>
</head>
<body>
    <canvas id="myid" width="500" height="500"></canvas>
    <script>
          //一通过回调函数来实现 1.加载图片 2.绘制图片

        //绘制图片
        function drawImageFn(imgEle){
            console.log('图片绘制函数执行了');
            let canvas =document.querySelector("#myid")
            let ctx = canvas.getContext("2d")
            ctx.drawImage(imgEle,0,0)
            
        }

        //加载图片
        function loadImg(src,cb){
            let imgEle =document.createElement('img');
            imgEle.src = src;
            imgEle.onload = function(){
                console.log('图片加载完毕了');
                cb&&cb(imgEle);
               
            }
            imgEle.onerror= function(){
                console.log('图片加载失败');

            }
        }
        let strurl = "https://gimg2.baidu.com/image_search/";//错误路径
        // let strurl = "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg.jj20.com%2Fup%2Fallimg%2Ftp09%2F21031FKU44S6-0-lp.jpg&refer=http%3A%2F%2Fimg.jj20.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1666333120&t=b1ca09200b10638ce39168c3c7542a40";

        // loadImg(strurl,function(imgEle){
        //         drawImageFn(imgEle);
        // })
        // loadImg(strurl, drawImageFn(imgEle))//这样不行，
        // loadImg(strurl) // 这样是在图片加载成功函数里直接调用了drawImageFn，
        // 可以成功，但是如果loadImg函数和drawImageFn函数不在一个页面，就没法实现的。


        //二通过promise来实现图片加载 1.加载图片 2.绘制图片

           //加载图片
           function loadImgPromise(src){
               return new Promise((resolve,rejected)=>{
                let imgEle =document.createElement('img');
                imgEle.src = src;

                imgEle.onload = function(){
                console.log('onload图片加载完毕了');
                resolve(imgEle);
               
            }
                imgEle.onerror= function(){
                console.log('onerror图片加载失败');
                rejected("reject图片加载失败")

            }
         })
        }

        loadImgPromise(strurl).then(res=>{
            drawImageFn(res)
        },err=>{
            console.log(err)
        })




    </script>
</body>
</html>